//
//  CCProgressView.m
//  didiAnimation
//
//  Created by iOS app dev on 17/2/21.
//  Copyright © 2017年 007qilv. All rights reserved.
//

#import "CCProgressView.h"
#import "CCProgress.h"

@interface CCProgressView ()

@property (nonatomic, strong) CCProgress *progressLayer;
@property (nonatomic, strong) NSTimer *timer;

@end

@implementation CCProgressView



- (instancetype)init
{
    if ((self = [super init])) {
        [self setupView];
    }
    return self;
}


- (instancetype)initWithFrame:(CGRect)frame
{
    if ((self = [super initWithFrame:frame])) {
        [self setupView];
    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    self.progressLayer.frame = self.bounds;
    
    [self.centerLabel sizeToFit];
    self.centerLabel.center = CGPointMake(self.center.x - self.frame.origin.x, self.center.y- self.frame.origin.y);
}


- (void)setupView
{
    self.backgroundColor = [UIColor clearColor];
    self.clipsToBounds = false;
    
    self.progressLayer = [[CCProgress alloc] init];
    self.progressLayer.frame = self.bounds;
    [self.layer addSublayer:self.progressLayer];
    
    _centerLabel = [[UILabel alloc] initWithFrame:self.bounds];
    _centerLabel.font = [UIFont systemFontOfSize:18];
    _centerLabel.textAlignment = NSTextAlignmentCenter;
    _centerLabel.textColor = [UIColor whiteColor];
    _centerLabel.text = @"已推送至 3 家";
    [self.layer addSublayer:_centerLabel.layer];
}


- (void)setAnimationTime:(NSTimeInterval)animationTime
{
    _animationTime = animationTime;
    [self.progressLayer setAnimtionTime:animationTime];
}


- (void)startAnimation
{
    if (!_timer) {
        _timer = [NSTimer timerWithTimeInterval:kAnimTimeInterval target:self selector:@selector(doTimerSchedule) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    }
    self.progressLayer.elapsedTime = 0;
    if (_start) _start();
}

- (void)doTimerSchedule
{
    self.progressLayer.elapsedTime = self.progressLayer.elapsedTime + kAnimTimeInterval;;
    if (_animing) _animing(self.progressLayer.elapsedTime);
    
    if (self.progressLayer.elapsedTime >= _animationTime) {
        [self stopAnimation];
    }
}


- (void)stopAnimation
{
    if (_stop) _stop();
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
    [_progressLayer stopAnimation];
}
@end
